package com.sywb.chuangyebao.contract;

import android.content.DialogInterface;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.ViewGroup;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.sywb.chuangyebao.Constants;
import com.sywb.chuangyebao.R;
import com.sywb.chuangyebao.bean.Channel;
import com.sywb.chuangyebao.view.NewsDetailActivity;
import com.sywb.chuangyebao.view.QAndADetailActivity;
import com.sywb.chuangyebao.view.TopicActivity;
import com.sywb.chuangyebao.view.TrainMediaDetailActivity;
import com.sywb.chuangyebao.view.TutorActivity;
import com.sywb.chuangyebao.view.UserMessageActivity;
import com.sywb.chuangyebao.view.VideoDetailActivity;
import com.sywb.chuangyebao.view.WebActivity;
import com.sywb.chuangyebao.view.dialog.ChannelDialogFragment;
import com.sywb.chuangyebao.view.fragment.BusinessTVFragment;
import com.sywb.chuangyebao.view.fragment.FollowFragment;
import com.sywb.chuangyebao.view.fragment.NewsFragment;
import com.sywb.chuangyebao.view.fragment.ProjectFragment;
import com.sywb.chuangyebao.view.fragment.RecommendFragment;
import com.sywb.chuangyebao.view.fragment.TrainFragment;
import com.sywb.chuangyebao.view.fragment.TutorFragment;
import com.sywb.chuangyebao.view.fragment.VideoFragment;
import com.sywb.chuangyebao.view.fragment.WebFragment;
import com.sywb.chuangyebao.widget.ColorTrackTabLayout;
import com.sywb.chuangyebao.widget.SuperViewPager;

import org.bining.footstone.log.Logger;
import org.bining.footstone.mvp.IView;
import org.bining.footstone.presenter.BasePresenter;
import org.bining.footstone.rxjava.rxbus.RxBus;
import org.bining.footstone.utils.ApkUtils;
import org.bining.footstone.utils.ScreenUtils;
import org.bining.footstone.utils.SharedUtils;
import org.bining.footstone.utils.ToastUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public interface HomeContract {

    interface View extends IView {

        FragmentManager getUserFragmentManager();

        ColorTrackTabLayout getTabLayout();

        SuperViewPager getViewPager();

        int getTabLayoutOffset();
    }

    class Presenter extends BasePresenter<View> {

        public String TITLE_SELECTED = "home_title_selected";
        public String TITLE_UNSELECTED = "home_title_unselected";

        private ColorTrackTabLayout tabLayout;
        private SuperViewPager viewpager;

        private List<Channel> mSelectedDatas;
        private List<Channel> mUnSelectedDatas;
        private List<Fragment> mFragments;
        private ChannelPagerFragmentAdapter fragmentPagerAdapter;

        boolean isShowMall = false;

        @Override
        public void onStart() {

            tabLayout = mView.getTabLayout();
            viewpager = mView.getViewPager();

            mSelectedDatas = new ArrayList<>();
            mUnSelectedDatas = new ArrayList<>();

            String selectTitle = SharedUtils.getString(TITLE_SELECTED, "");
            String unselectTitle = SharedUtils.getString(TITLE_UNSELECTED, "");
            if (TextUtils.isEmpty(selectTitle)) {
                String[] titleStr = mContext.getResources().getStringArray(R.array.home_title);
                int[] titlesCode = mContext.getResources().getIntArray(R.array.home_title_code);
                //默认添加了全部频道
                for (int i = 0; i < titlesCode.length; i++) {
                    String t = titleStr[i];
                    int code = titlesCode[i];
                    mSelectedDatas.add(new Channel(t, code));
                }
                SharedUtils.put(TITLE_SELECTED, JSON.toJSONString(mSelectedDatas));
                SharedUtils.put(TITLE_UNSELECTED, "");
            } else {
                List<Channel> selecteData = JSON.parseArray(selectTitle, Channel.class);
                mSelectedDatas.addAll(selecteData);
                if (!TextUtils.isEmpty(unselectTitle)) {
                    List<Channel> unselecteData = JSON.parseArray(unselectTitle, Channel.class);
                    mUnSelectedDatas.addAll(unselecteData);
                }
            }

            initView();
        }

        public void setShowMallView(boolean isShowMall) {
            viewpager.setShowMall(isShowMall);
        }

        public void initView() {
            mFragments = new ArrayList<>();
            for (int i = 0; i < mSelectedDatas.size(); i++) {
                Channel channel = mSelectedDatas.get(i);
                Fragment fragment = null;
                switch (channel.TitleCode) {
                    case 10:
                        fragment = FollowFragment.newInstance();
                        break;
                    case 11:
                        fragment = RecommendFragment.newInstance(0);
                        break;
                    case 12:
                        fragment = NewsFragment.newInstance(-1);
                        break;
//                    case 13:
//                        fragment = QAndAListFragment.newInstance(0);
//                        break;
                    case 14:
                        fragment = VideoFragment.newInstance(0, -1);
                        break;
                    case 15:
                        fragment = BusinessTVFragment.newInstance(0);
                        break;
                    case 16:
                        fragment = ProjectFragment.newInstance();
                        break;
                    case 17:
                        fragment = TutorFragment.newInstance();
                        break;
                    case 18:
                        fragment = TrainFragment.newInstance();
                        break;
                    case 19:
                        fragment = WebFragment.newInstance(2, "http://dh.3158.cn/");
                        break;
                }
                mFragments.add(fragment);
            }
            fragmentPagerAdapter = new ChannelPagerFragmentAdapter(mView.getUserFragmentManager(), mFragments, mSelectedDatas);

            viewpager.setAdapter(fragmentPagerAdapter);
            viewpager.setOffscreenPageLimit(mSelectedDatas.size());
            viewpager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                @Override
                public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                }

                @Override
                public void onPageSelected(int position) {
                    RxBus.get().post(Constants.HOMETABCHANGE, fragmentPagerAdapter.getPageTitle(position));
                }

                @Override
                public void onPageScrollStateChanged(int state) {

                }
            });

            tabLayout.setTabPaddingLeftAndRight(ScreenUtils.dp2px(10), ScreenUtils.dp2px(10));
            tabLayout.setupWithViewPager(viewpager);
            tabLayout.post(new Runnable() {
                @Override
                public void run() {
                    //设置最小宽度，使其可以在滑动一部分距离
                    ViewGroup slidingTabStrip = (ViewGroup) tabLayout.getChildAt(0);
                    if (slidingTabStrip != null && mView != null) {
                        slidingTabStrip.setMinimumWidth(slidingTabStrip.getMeasuredWidth() + mView.getTabLayoutOffset());
                    }
                }
            });
            //隐藏指示器
            tabLayout.setSelectedTabIndicatorHeight(0);

            tabLayout.setCurrentItem(1);
        }

        public void goTutor() {
            int postion = -1;
            if (mSelectedDatas != null) {
                for (int i = 0; i < mSelectedDatas.size(); i++) {
                    Channel channel = mSelectedDatas.get(i);
                    if (channel.TitleCode == 17) {
                        postion = i;
                        break;
                    }
                }
            }
            if (postion >= 0) {
                tabLayout.setCurrentItem(postion);
            } else {
                mView.advance(TutorActivity.class);
            }
        }

        public boolean goBusinessTV() {
            int postion = -1;
            if (mSelectedDatas != null) {
                for (int i = 0; i < mSelectedDatas.size(); i++) {
                    Channel channel = mSelectedDatas.get(i);
                    if (channel.TitleCode == 15) {
                        postion = i;
                        break;
                    }
                }
            }
            if (postion >= 0) {
                tabLayout.setCurrentItem(postion);
                return true;
            }
            return false;
        }

        public void goManager() {
            ChannelDialogFragment dialogFragment = ChannelDialogFragment.newInstance(mSelectedDatas, mUnSelectedDatas);
            dialogFragment.setOnChannelListener(new ChannelDialogFragment.OnChannelListener() {

                @Override
                public void onItemMove(int itemType, int starPos, int endPos) {
                    Logger.e("onItemMove itemType:" + itemType + " starPos:" + starPos + " endPos" + endPos);
                    if (itemType == Channel.TYPE_MY_CHANNEL) {
                        mSelectedDatas.add(endPos, mSelectedDatas.remove(starPos));
                        // mFragments.add(endPos, mFragments.remove(starPos));
                    } else {
                        mUnSelectedDatas.add(endPos, mUnSelectedDatas.remove(starPos));
                    }
                }

                @Override
                public void onMoveToMyChannel(int starPos, int endPos) {
                    Logger.e("onMoveToMyChannel starPos:" + starPos + " endPos" + endPos);
                    Channel channel = mUnSelectedDatas.remove(starPos);
                    mSelectedDatas.add(endPos, channel);
                    // mFragments.add(OtherFragment.newInstance(channel.TitleCode));
                }

                @Override
                public void onMoveToOtherChannel(int starPos, int endPos) {
                    Logger.e("onMoveToOtherChannel starPos:" + starPos + " endPos" + endPos);
                    mUnSelectedDatas.add(endPos, mSelectedDatas.remove(starPos));
                    // mFragments.remove(starPos);
                }
            });

            dialogFragment.show(mView.getUserFragmentManager(), "CHANNEL");
            dialogFragment.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {

                    //保存选中和未选中的channel
                    SharedUtils.put(TITLE_SELECTED, JSON.toJSONString(mSelectedDatas));
                    SharedUtils.put(TITLE_UNSELECTED, JSON.toJSONString(mUnSelectedDatas));

                    ViewGroup slidingTabStrip = (ViewGroup) tabLayout.getChildAt(0);
                    if (slidingTabStrip != null) {
                        //注意：因为最开始设置了最小宽度，所以重新测量宽度的时候一定要先将最小宽度设置为0
                        slidingTabStrip.setMinimumWidth(0);
                        slidingTabStrip.measure(0, 0);
                        slidingTabStrip.setMinimumWidth(slidingTabStrip.getMeasuredWidth() + mView.getTabLayoutOffset());
                    }
                    initView();
                }
            });
        }
    }

    class ChannelPagerFragmentAdapter extends FragmentStatePagerAdapter {

        private List<Fragment> fragments;
        private List<Channel> channels;

        public ChannelPagerFragmentAdapter(FragmentManager fragmentManager, List<Fragment> fragments, List<Channel> channels) {
            super(fragmentManager);
            this.fragments = fragments;
            this.channels = channels;
        }

        @Override
        public Fragment getItem(int position) {
            return fragments.get(position);
        }

        @Override
        public int getCount() {
            return channels.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return channels == null ? "" : channels.get(position).Title;
        }

        @Override
        public int getItemPosition(Object object) {
            return POSITION_NONE;
        }
    }

}

